package com.bonc.common.sso;

import com.alibaba.fastjson.JSONObject;
import com.bonc.common.utils.*;
import com.bonc.modules.sys.entity.SysUserEntity;
import com.bonc.modules.sys.entity.SysUserTokenEntity;
import com.bonc.modules.sys.service.ShiroService;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;


/**
 *
 * @Title: 集团大音单点登录
 * @Description: 在省大音跳转集团大音
 * @Author:weixiaoguang
 * @Since:2021年10月29日
 * @Version:1.1.0
 */
@RestController
@RequestMapping(value = "/ssoJtdy")
public class SsoJtdyRestFul {
	private Log log = LogFactory.getLog(this.getClass());

	@Value("${oa.JtdyUrl}")
	private String jtdyUrl;
	@Value("${oa.PjreqUrl}")
	private String pjreqUrl;
	@Autowired
	private ShiroService shiroService;


	/**
	 *在省大音跳转集团大音
	 * @param request
	 */
	@RequestMapping(value = "/jtdyLogin",produces = "application/json;charset=utf-8")
	public Result sso(HttpServletRequest request) {
		String url = "";
		try{
			//从header中获取token
			String token = request.getHeader("token");
			println("=======进入省大音跳转集团大音接口，用户token======="+token);
			//如果header中不存在token，则从参数中获取token
			if(StringUtils.isBlank(token)){
				token = request.getParameter("token");
			}
			if(!StringUtils.isBlank(token)){
				SysUserTokenEntity tokenEntity = shiroService.queryByToken(token);
				//根据token获取用户信息
				SysUserEntity user = shiroService.queryUser(tokenEntity.getUserId());
				//请求头参数准备***************
				String reqid = "699072962913281";//固定
				String appcode = "NGBOSS";//固定
				String systime = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
				String nonce= UUID.randomUUID().toString().replace("-", "");
				String salt = DigestUtils.md5Hex(systime+nonce);
				String API_KEY_DEFAULT = "25d55ad283aa400af464c76d713c07ad";//服务方的apikey
				String apikey = DigestUtils.md5Hex(API_KEY_DEFAULT + salt);//请求方的apikey
				println("=======票据申请接口请求头参数apikey======="+apikey);
				Map headmap = new HashMap();
				headmap.put("apikey", apikey);
				headmap.put("reqid", reqid);
				headmap.put("appcode", appcode);
				headmap.put("systime", systime);
				headmap.put("nonce", nonce);
				println("=======票据申请接口请求头headmap======="+headmap);
				//请求体参数准备***************
				String appCode = "NGBOSS";//单点登录的目标应用的应用编码
				String appLoginAcct = user.getUsername();//当前应用使用的帐号登录名
				println("=======当前应用使用的帐号登录名======="+appLoginAcct);
				//appLoginAcct = DES.desEncryptData(appLoginAcct);//帐号登录名3des加密
				//String mobile = user.getMobile();
				//println("=======当前应用使用的帐号手机号======="+mobile);
				//mobile = DES.desEncryptData(mobile);//手机号3des加密
				String ip = IPUtils.getIpAddr(request);//ip地址获取
				String mac = "";
				String cpu = "";
				String targetappcode = "JTNGCSVC";
				if(!StringUtils.isBlank(appLoginAcct)){
					JSONObject jObj = new JSONObject();
					jObj.put("appCode", appCode);
					jObj.put("appLoginAcct", appLoginAcct);
					//jObj.put("mobile", mobile);
					jObj.put("ip", ip);
					jObj.put("mac", mac);
					jObj.put("cpu", cpu);
					jObj.put("targetappcode", targetappcode);
					String reqbody = jObj.toString();
					println("=======票据申请接口请求体参数加密前======="+reqbody);
					//请求体加密
					String reqbodyencry = AsiaCipher.encrypt(reqbody,apikey);
					println("=======票据申请接口请求体参数加密后======="+reqbodyencry);
					//调用单点登录应用票据申请接口
					String result = "";
					try{
						//String result = HttpUtils.doPost(pjreqUrl, reqbodyencry);
						HttpContext localContext = new BasicHttpContext();
						result= HttpUtil.httpPostJsonOrXml(localContext, pjreqUrl, reqbodyencry, headmap, "UTF-8", 1000*10);
						println("=======票据申请接口返回结果未解密======="+result);
					}catch (Exception e){
						this.log.error("", e);
						return  Result.error("票据申请接口出错"+e.getMessage());
					}
					//响应体解密
					String resparam = "";
					try{
						resparam = AsiaCipher.dencrypt(result, apikey);
						println("=======票据申请接口返回结果解密后======="+resparam);
					}catch (Exception e){
						return  Result.error("票据申请接口返回结果解密出错"+e.getMessage());
					}
					//从响应中获取票据ssoToken
					String returnCode = "";
					String pjtoken = "";
					String appAcctId = "";
					String msg = "";
					Map<String, Object> resultMap = MapUtils.json2Map(resparam);
					returnCode = resultMap.get("returnCode") == null ? "失败" : resultMap.get("returnCode").toString();
					//returnCode = resultMap.get("returnCode").toString();
					println("=======票据接口返回成功标识0成功非0失败======="+returnCode);
					if("0".equals(returnCode)){
						pjtoken = resultMap.get("token").toString();
						appAcctId = resultMap.get("appAcctId").toString();
						//跳转集团单点登录url
						//http://ip:port/4a_login?orgsys=&appAcctId=xxx&token=xxx&flag=xxx
						url = jtdyUrl+"?orgsys=SX&appAcctId="+appAcctId+"&token="+pjtoken+"&flag=1";//集团接口地址
						println("=======集团大音单点登录url=======" + url);
					}else{
						msg = resultMap.get("msg").toString();
						println("=======票据获取失败======="+msg);
						return  Result.error("票据获取失败");
					}
				}
			}
		}catch (Exception e){
			e.printStackTrace();
			return  Result.error("未知异常,请联系管理员"+e.getMessage());
		}
		return Result.ok().put("url",url);
	}
	public void println(String msg) {
		System.out.println(Thread.currentThread().getName() + " : " + msg);
	}
}
